package main

import "fmt"
import "net/http"
import "time"
import "os"

import (
	"gopkg.in/ini.v1"
	"demo_use/utils"
)

func Log(response http.ResponseWriter, req *http.Request){
	//http://192.168.71.21:8081?act=1&api=login&partid=1000&gid=100&sid=s1
//	query := req.URL.Query()
	api := req.PostFormValue("api")
	partId := req.PostFormValue("part_id")
	gid := req.PostFormValue("gid")
	sid := req.PostFormValue("sid")
//	fmt.Fprintf(response,get_act)
	//日志路径
	now := time.Now()
	logDirYmd  := fmt.Sprintf("./%s/%s/%s/%04d/%02d/%02d/",partId,gid,sid,now.Year(),now.Month(),now.Day())
	dirRes,_ := utils.Mkdir(logDirYmd)
	if dirRes {
	 	filename :=	logDirYmd+fmt.Sprintf("%s_%02d.txt",api,now.Hour())
		//获取配置文件的key
		cfg, err := ini.Load("table.ini")
		if err != nil {
			fmt.Printf("Fail to read file: %v", err)
			os.Exit(1)
		}
		comonKeys := cfg.Section("common").KeyStrings()
		apiKeys := cfg.Section(api).KeyStrings()
		allKeysLen := len(comonKeys)+len(apiKeys)
		list := make([]string,allKeysLen)
		copy(list,comonKeys)
		copy(list[len(comonKeys):],apiKeys)
		message := ""
		errMessage := ""
		for _,r := range list{
			queryReq := req.PostFormValue(r)
			if len(queryReq)==0 {
				//query[req][0]
				errMessage = errMessage+","+r
				//fmt.Fprintf(response,req+":"+query[req][0]+"\n")
			}else{
				message = message+queryReq+","
			}
		}
		if errMessage != "" {
			errMessage = errMessage[0:len(errMessage)-1]
			errMessage = errMessage+" is required"
			fmt.Fprintf(response, utils.JsonEncode(-1,errMessage,""))
		}else{
			message = message[0:len(message)-1]
			message = message+"\n"
			if utils.FilePutContents(filename,message,true) {
				fmt.Fprintf(response, utils.JsonEncode(0,"",""))
			}
		}
	}else{
		fmt.Fprintf(response, utils.JsonEncode(-1,"dir error",""))
	}
	//创建日志路径
}

func main(){
	http.HandleFunc("/",Log)
	http.ListenAndServe(":8081",nil)
}